﻿using AspectCore.DynamicProxy;
using Spectre.Console;
using System.Text.Json;
using System.Text.Json.Serialization;
using Zy.Shared.Audit.LogEntity;
using Zy.Shared.Repository.ClickHouse.Repositorys;
using Zy.Shared.YitterHelper.Services;

namespace Zy.Shared.Audit.Interceptors
{
    /// <summary>
    /// 审计拦截器
    /// </summary>
    /// <param name="OperationName">操作名称</param>
    public class AuditInterceptorAttribute(string OperationName) : AbstractInterceptorAttribute
    {
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
           try
            {
                Console.WriteLine($"Before service call,{OperationName}");
               
                await next(context);
            }
            catch (Exception)
            {
                Console.WriteLine("Service throw an exception!");
                throw;
            }
            finally
            {
                Console.WriteLine("After service call.");
                var service = (ISqlSugarRespository<AuditLogEntity>)context.ServiceProvider.GetService(typeof(ISqlSugarRespository<AuditLogEntity>));
                if (service != null)
                {
                    var log = new AuditLogEntity()
                    {
                        Id= ZyIdGenerator.NextId(),
                        OperationName = OperationName,
                        MethodName = context.ServiceMethod.Name,
                        Parameters = Newtonsoft.Json.JsonConvert.SerializeObject(context.Parameters),
                        //ReturnValue = Newtonsoft.Json.JsonConvert.SerializeObject(((Task)context.ReturnValue)),
                    };
                    await service.InsertAsync(log);
                }
            }
        }
    }
}
